<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form :label-width="90">
        <!-- <FormItem label="分类：">
                    <TagSelect ref="labelList" :expandable="status" :class="{ 'labelList': !status }" v-model="type" @on-change="onSearch">
                        <TagSelectOption v-for="(part, index) in headSelectedList" :key="'part-'+index" :name="part.id">{{part.name}}</TagSelectOption>
                    </TagSelect>
                </FormItem>
                <Divider dashed /> -->
        <Row type="flex" style="justify-content: space-between;">
          <div style="display: flex;">
            <FormItem>
              <Select
                style="width:300px"
                v-model="modelTime"
                @on-change="selectTimeImage"
                filterable
                multiple
                :max-tag-count="2"
              >
                <Option
                  v-for="(item, index) in orderTime"
                  :value="item"
                  :key="'item' + index"
                >
                  {{ item }}
                </Option>
              </Select>
            </FormItem>

            <FormItem style="margin-left:30px">
              <RadioGroup v-model="order" @on-change="onSearch">
                <Radio label="1">顺序时间</Radio>
                <Radio label="0">倒序时间</Radio>
              </RadioGroup>
            </FormItem>
          </div>
          <div>
            <Col v-if="edit">
              <ButtonGroup>
                <Button class="v-mt-20" size="default">
                  <a
                    :href="`baiyou://${patientCardId}`"
                    type="default"
                    size="large"
                    >本地图片</a
                  ></Button
                >
                <Button @click="resetPartSel" class="v-mt-20" size="default"
                  >取消</Button
                >
                <Button
                  :disabled="!delSel.length"
                  @click="delPart"
                  type="error"
                  class="v-mt-20"
                  size="default"
                  >删除</Button
                >
                <Button
                  @click="submitSave"
                  type="primary"
                  class="v-mt-20"
                  size="default"
                  >保存</Button
                >
              </ButtonGroup>
            </Col>
            <Col v-else>
              <ButtonGroup>
                <Button class="v-mt-20" size="default">
                  <a
                    :href="`baiyou://${patientCardId}`"
                    type="default"
                    size="large"
                    >本地图片</a
                  ></Button
                >
                <Button
                  @click="edit = true"
                  type="primary"
                  class="v-mt-20"
                  size="default"
                  >编辑</Button
                >
              </ButtonGroup>
            </Col>
          </div>
        </Row>
      </Form>
    </Card>
    <Row v-if="edit" :gutter="30" class="ivu-mt images">
      <CheckboxGroup v-model="delSel">
        <!-- <Col :xl="compact ? 12 : 6" :lg="compact ? 12 : 8" :md="12" :sm="12" :xs="24" -->
        <Col
          span="8"
          v-for="(items, index) in projectList"
          :key="index"
          class="ivu-mb"
        >
          <div
            :bordered="bordered"
            dis-hover
            :padding="0"
            class="search-search-projects-item"
          >
            <div class="imgArea">
              <img
                @error="imgError(items)"
                :src="items.img_thumb_url ? items.img_thumb_url : items.img_url"
                :data-source="
                  items.img_url ? items.img_url : items.img_thumb_url
                "
                class="search-search-projects-item-cover"
              />
            </div>
            <div class="ivu-p-8">
              <div
                class="search-search-projects-item-extra"
                style="display: flex;justify-content: space-between;align-items: center;"
              >
                <span style="line-height: 30px">
                  {{ items.created_at_str }}
                </span>
                <span style="display: flex;align-items: center;">
                  <span>
                    <Checkbox :label="items.id" class="checkSelBot"></Checkbox>
                  </span>
                  <span class="ivu-fr">
                    <Select v-model="partSel[index].body_parts_id">
                      <Option
                        v-for="item in bodyList"
                        :value="item.id"
                        :key="item.id"
                        >{{ item.name }}
                      </Option>
                    </Select>
                  </span>
                </span>
              </div>
            </div>
          </div>
        </Col>
      </CheckboxGroup>
    </Row>
    <Row
      v-else
      :gutter="30"
      class="ivu-mt images"
      v-viewer="{ movable: false }"
    >
      <Col
        span="8"
        v-for="(items, index) in projectList"
        :key="index"
        class="ivu-mb"
      >
        <div dis-hover :padding="0" class="search-search-projects-item">
          <div class="imgArea">
            <img
              @error="imgError(items)"
              :src="items.img_thumb_url ? items.img_thumb_url : items.img_url"
              :data-source="items.img_url ? items.img_url : items.img_thumb_url"
              class="search-search-projects-item-cover"
            />
          </div>
          <div class="ivu-p-8">
            <div class="search-search-projects-item-extra ivu-mt-8 ivu-pb-8">
              <span>
                {{ items.created_at_str }}
              </span>
              <span class="ivu-fr">
                {{ items.body_parts_name }}
              </span>
            </div>
          </div>
        </div>
      </Col>
      <div
        class="ivu-text-center only-bottom"
        v-if="!empty && projectList.length"
      >
        <Button v-if="!edit" type="primary" @click="getMoreData"
          >加载更多</Button
        >
      </div>
    </Row>
    <div class="ivu-text-center only-bottom" v-if="empty">
      <span v-if="projectList.length === 0">暂无治疗图片</span>
      <span v-else>——图片全部加载完毕——</span>
    </div>
  </div>
</template>
<script>
import {
  PatientClinicImgList,
  PatientClinicImgEdit,
  PatientClinicImgDelete,
} from "@api/patient";
export default {
  name: "detailed-Images",
  props: {
    compact: {
      type: Boolean,
      default: false,
    },
    bordered: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      status: false,
      loading: false,
      partSel: [],
      type: [],
      order: "0",
      modelTime: [],
      orderTime: [],
      projectList: [],
      single: false,
      bodyList: [],
      // 备注： 组件bug, 添加初始占位值
      headSelectedList: [{ id: "0", name: "" }],
      patientCardId: "",
      edit: false,
      delSel: [],
      errorUserPhoto:
        "https://dev-file.iviewui.com/WLXm7gp1EbLDtvVQgkeQeyq5OtDm00Jd/middle",
      page: 1,
      pageSize: 6,
      empty: false,
      timer: false,
      screenWidth: 0,
      state: true,
    };
  },
  methods: {
    imgError(item) {
      item.img_url = this.errorUserPhoto;
    },
    initResize() {
      const that = this;
      window.onresize = () => {
        if (this.state) {
          this.state = false;
          that.labelList();
          setTimeout(() => {
            that.state = true;
          }, 300);
        }
      };
    },
    // 根据时间查询图片
    selectTimeImage() {
      this.status = false;
      this.page = 1;
      this.empty = false;
      this.projectList = [];
      this.patientClinicImgList();
    },
    getData(id) {
      this.patientCardId = id;
      this.projectList = [];
      this.orderTime = [];
      this.status = false;
      this.page = 1;
      this.empty = false;
      this.patientClinicImgList();
      this.initResize();
    },
    getMoreData() {
      this.page = this.page + 1;
      this.patientClinicImgList();
    },
    patientClinicImgList() {
      const params = {
        patient_card_id: this.patientCardId,
        sort_created_at_type: this.order,
        page: this.page,
        pageSize: this.pageSize,
        img_date: this.modelTime.join(","),
      };
      if (this.type.length !== this.bodyList.length) {
        params.body_parts_id = this.type.join(",");
      }
      PatientClinicImgList(params)
        .then((res) => {
          // console.log(res)
          if (!res.list.length || res.list.length < 6) this.empty = true;
          this.bodyList = res.condition.body_parts_list;
          this.headSelectedList = res.condition.select_body_parts_list;
          this.projectList = this.projectList.concat(res.list);
          this.orderTime = res.condition.date_list || [];
          this.partSel = this.filterSel(this.projectList);
          // if ((this.page * this.pageSize) >= res.total || !res.list.length) {
          //     this.empty = true
          // }
          this.loading = false;
          this.labelList();
        })
        .catch(() => {});
    },
    // 判断标签个数
    labelList() {
      this.status = false;
      this.$nextTick(() => {
        const height =
          this.$refs.labelList && this.$refs.labelList.$el.offsetHeight;
        if (height > 32) this.status = true;
        else this.status = false;
      });
    },
    filterSel(arr) {
      let reArr = [];
      if (arr && arr.length > 0) {
        arr.forEach((items) => {
          const reItem = {
            id: items.id,
            body_parts_id: items.body_parts_id,
          };
          reArr.push(reItem);
        });
      }
      return reArr;
    },
    resetPartSel() {
      this.partSel = this.filterSel(this.projectList);
      this.delSel = [];
      this.edit = false;
    },
    delPart() {
      const param = {
        ids: this.delSel.join(","),
      };
      const length = this.delSel.length;
      this.$Modal.confirm({
        title: "删除治疗图片",
        content: "确定删除这" + length + "张图片?",
        onOk: () => {
          this.delSel = [];
          this.deleteSubmit(param);
        },
        onCancel: () => {},
      });
    },
    deleteSubmit(param) {
      PatientClinicImgDelete(param)
        .then((res) => {
          this.$Message.success(" 删除图片成功");
          this.loading = false;
          this.edit = false;
          this.projectList = [];
          this.patientClinicImgList();
        })
        .catch(() => {});
    },
    submitSave() {
      const params = {
        patient_card_id: parseInt(this.patientCardId),
        clinic_imgs: JSON.stringify(this.partSel),
      };
      this.loading = true;
      PatientClinicImgEdit(params)
        .then((res) => {
          this.$Message.success("提交保存成功！");
          this.loading = false;
          this.onSearch();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onSearch() {
      this.edit = false;
      this.page = 1;
      this.empty = false;
      this.projectList = [];
      this.patientClinicImgList();
    },
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          // 打印screenWidth变化的值
          that.timer = false;
        }, 400);
      }
    },
  },
  destroyed() {
    window.removeEventListener("onresize", (e) => this.labelList());
  },
};
</script>
<style lang="less" scoped>
/deep/.ivu-checkbox + span {
  display: none;
}

.ivu-footer-toolbar {
  width: 1000px;
}

.only-bottom {
  padding-bottom: 40px;
}

.search-search-projects {
  &-item {
    box-sizing: border-box;
    width: 100%;
    padding: 0 8%;
    /* display: flex; */
    /* justify-content: center;
            align-items: center; */

    .imgArea {
      height: 160px;
      width: 100%;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .checkSel {
      .ivu-checkbox {
        display: none;
      }
    }

    .ivu-checkbox-wrapper {
      margin-right: 0;

      .ivu-checkbox {
        position: absolute;
        top: 4px;
        left: 4px;
        z-index: 999;
      }
    }

    &-cover {
      width: 100%;
      border-radius: 4px 4px 0 0;
    }

    &-desc {
      display: -webkit-box;
      height: 40px;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    &-extra {
      span {
        display: inline-block;
        color: #808695;
        vertical-align: middle;
        margin-left: 10px;
      }
    }
  }
}

.labelList {
  max-height: none;
}

/deep/.ivu-form-item-content {
  margin-left: 0 !important;
}
</style>
